#include "Connection.hpp"
class Channel : public Connection
{
public:
    Channel(int fd, InetAddr client)
        : _fd(fd), _client(client)
    {
    }
    virtual void Recver()
    {
        //cout<<"Channel Recver..."<<endl;
        char buffer[1024];
        while (true)
        {
            buffer[0] = 0;
            int n = recv(_fd, buffer, sizeof(buffer)-1, 0);
            if (n > 0)
            {
                buffer[n]=0;
                _inbuffer+=buffer;
            }
            else if (n == 0)
            {
                //LOG(Level::INFO) << "client out" << _fd;
                GetOwner()->DelConnection(_fd);
                break;
            }
            else
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    Excepter();
                    return;
                }
            }
            //cout<<"Channel Recver out..."<<endl;
        }
        if(!_inbuffer.empty())
        {
            //回调协议层处理
            _outbuffer += GetHandler()(_inbuffer);
        }
        if(!_outbuffer.empty())
        {
            Sender();
            //或
            //GetOwner()->EnableReadWrite(_fd,true,true);
        }
    }
    virtual void Sender()
    {
        while (true)
        {
            int n = send(_fd, _outbuffer.c_str(), _outbuffer.size(), 0);
            if (n > 0)
            {
                _outbuffer.erase(0, n);
                if (_outbuffer.empty())
                    break;
            }
            else if (n == 0)
            {
                break;
            }
            else
            {
                if (errno == EAGAIN || errno == EWOULDBLOCK)
                    break;
                else if (errno == EINTR)
                    continue;
                else
                {
                    Excepter();
                    return;
                }
            }
        }
        if(!_outbuffer.empty())
        {
            GetOwner()->EnableReadWrite(_fd,true,true);
        }
        else
        {
            GetOwner()->EnableReadWrite(_fd,true,true);
        }
    }
    virtual int GetFd()
    {
        return _fd;
    }
    void Excepter()
    {
        //所有异常处理
        GetOwner()->DelConnection(_fd);
    }
    ~Channel()
    {
    }

private:
    int _fd;
    InetAddr _client;
    string _inbuffer;
    string _outbuffer;
};